package controller;

import common.*;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.util.Callback;
import ui.Main;
import util.FlushCourse;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.Vector;

public class TeacherCourseController implements Initializable {
    private Socket socket= Main.userClientService.getSocket();
    private Course course;
    public TeacherCourseController(Course course) {
        this.course=course;
    }
    @FXML
    private Label courseName;
    @FXML
    private Label ID;
    @FXML
    private Label code;
    @FXML
    private ListView<User> student;
    private ObservableList<User> user = FXCollections.observableArrayList();//学生列表数据源
    @FXML
    private TabPane tabPane;
    @FXML
    private Tab tab1;
    private boolean flag=true;
    private Thread thread;
    @Override
    public void initialize(URL location, ResourceBundle resources) {
        courseName.setText(course.getName());
        ID.setText(String.format("%0" + 8 + "d", Integer.parseInt(course.getId())));
        code.setText(course.getCode());
        flush(course.getStudent());
        student.setItems(user);
        student.setCellFactory(new Callback<ListView<User>, ListCell<User>>() {
            @Override
            public ListCell<User> call(ListView<User> param) {
                return new ListCell<User>() {
                    @Override
                    protected void updateItem(User user, boolean empty) {
                        super.updateItem(user, empty);
                        if (empty || user == null) {
                            setText(null);
                            setStyle(""); // 清除样式
                        } else {
                            setText(user.getName()+" - "+"学号"+user.getNumber());
                            if (user.getState()==User.onLine) { // 设置单元格的背景颜色
                                setTextFill(Color.WHITE);
                                setStyle("-fx-background-color: green;");//在线就设置成绿色
                            } else { // 其他单元格不设置背景颜色
                                setTextFill(Color.BLACK);
                                setStyle("");
                            }
                        }
                    }
                };
            }
        });
        student.setOnMouseClicked(event -> {
            if (event.getClickCount() == 2) {
                // 获取双击时选中的项
                User selectedItem = student.getSelectionModel().getSelectedItem();
                if (selectedItem==null) return;
                Stage stage=new Stage();
                FXMLLoader loader=null;
                DeleStuController deleStuController=new DeleStuController(selectedItem,course,this);
                Pane root=null;
                loader=new FXMLLoader(getClass().getResource("/Interface/DeleStu.fxml"));
                loader.setController(deleStuController);
                try {
                    root=loader.load();
                } catch (IOException e) {
                    System.out.println("双击跳转学生资料界面失败");
                    e.printStackTrace();
                }
                Scene scene=new Scene(root);
                stage.setScene(scene);
                stage.getIcons().add(new Image("/Interface/Icon.png"));
                stage.setTitle(selectedItem.getName());
                stage.setResizable(false);
                stage.show();
            }
        });
        flag = true;
        if (service.getState() == Service.State.CANCELLED) {
            // 当 Service 处于 CANCELLED 状态时重新创建一个新的 MyService 实例
            service = new MyService();
        }
        if (!service.isRunning()) {
            // 只有当 Service 未运行时才启动 Service
            service.start();
        }

        // 在 Tab 被选中时启动 Service
        tab1.setOnSelectionChanged(event -> {
            if (tab1.isSelected()) {
                flag = true;
                if (service.getState() == Service.State.CANCELLED) {
                    // 当 Service 处于 CANCELLED 状态时重新创建一个新的 MyService 实例
                    service = new MyService();
                }
                if (!service.isRunning()) {
                    // 只有当 Service 未运行时才启动 Service
                    service.start();
                }
            } else {
                close();
            }
        });
        selectFlush();
        selectlist.setItems(selectTask);
        selectlist.setCellFactory(new Callback<ListView<Select>, ListCell<Select>>() {
            @Override
            public ListCell<Select> call(ListView<Select> param) {
                return new ListCell<Select>() {
                    @Override
                    protected void updateItem(Select select, boolean empty) {
                        super.updateItem(select, empty);
                        if (empty || select == null) {
                            setText(null);
                        } else {
                            setText(String.format("%0" + 5 + "d", selectTask.size()-selectTask.indexOf(select))+" - "+select.getName());
                        }
                    }
                };
            }
        });
        selectlist.setOnMouseClicked(event -> {
            if (event.getClickCount() == 2) {
                // 获取双击时选中的项
                Select selectedItem = selectlist.getSelectionModel().getSelectedItem();
                if(selectedItem==null) return;
                Stage stage=new Stage();
                FXMLLoader loader=null;
                SelectPeopController selectPeopController=new SelectPeopController(selectedItem,FlushCourse.studentMap.get(course.getId()));
                Pane root=null;
                loader=new FXMLLoader(getClass().getResource("/Interface/SelectPeop_.fxml"));
                loader.setController(selectPeopController);
                try {
                    root=loader.load();
                } catch (IOException e) {
                    System.out.println("双击跳转选人界面失败");
                    e.printStackTrace();
                }
                Scene scene=new Scene(root);
                stage.setScene(scene);
                stage.getIcons().add(new Image("/Interface/Icon.png"));
                stage.setTitle(String.format("%0" + 5 + "d", selectTask.size()-selectTask.indexOf(selectedItem))+" - "+selectedItem.getName());
                stage.setResizable(false);
                stage.show();
            }
        });
        for(int i=0;i<FlushCourse.topicMap.get(course.getId()).size();i++){
            topicSource.add(0,FlushCourse.topicMap.get(course.getId()).get(i));
        }
        topiclist.setItems(topicSource);
        topiclist.setCellFactory(new Callback<ListView<Topic>, ListCell<Topic>>() {
            @Override
            public ListCell<Topic> call(ListView<Topic> param) {
                return new ListCell<Topic>() {
                    @Override
                    protected void updateItem(Topic topic, boolean empty) {
                        super.updateItem(topic, empty);
                        if (empty || topic == null) {
                            setText(null);
                        } else {
                            setText(String.format("%0" + 4 + "d", topicSource.size()- getIndex())+" - "+topic.getTitle());
                        }
                    }
                };
            }
        });
        topiclist.setOnMouseClicked(event->{
            if (event.getClickCount() == 2) {
                // 获取双击时选中的项
                Topic selectedItem = topiclist.getSelectionModel().getSelectedItem();
                if(selectedItem==null) return;
                selectedItem.setCourse(course);
                Stage stage=new Stage();
                FXMLLoader loader=null;
                CompleteListController completeListController=new CompleteListController(selectedItem);
                Pane root=null;
                loader=new FXMLLoader(getClass().getResource("/Interface/CompleteList.fxml"));
                loader.setController(completeListController);
                try {
                    root=loader.load();
                } catch (IOException e) {
                    System.out.println("双击跳转批阅界面失败");
                    e.printStackTrace();
                }
                Scene scene=new Scene(root);
                stage.setScene(scene);
                stage.getIcons().add(new Image("/Interface/Icon.png"));
                stage.setTitle(String.format("%0" + 4 + "d", topicSource.size()-topicSource.indexOf(selectedItem))+" - "+selectedItem.getTitle());
                stage.setResizable(false);
                stage.show();
                topicSource.clear();
                for(int i=0;i<FlushCourse.topicMap.get(course.getId()).size();i++){
                    topicSource.add(0,FlushCourse.topicMap.get(course.getId()).get(i));
                }
            }
        });
    }
    private MyService service = new MyService();

    // 创建一个继承自 Service 类的子类
    private class MyService extends Service<Void> {
        @Override
        protected Task<Void> createTask() {
            // 创建一个任务，用于执行后台操作
            return new Task<Void>() {
                @Override
                protected Void call() throws Exception {
                    while (flag) {
                        Thread.sleep(3000);
                        Platform.runLater(() -> {
                            flush(FlushCourse.studentMap.get(course.getId()));
                            System.out.println("刷新学生列表");
                        });
                    }
                    return null;
                }
            };
        }
    }
    @FXML
    public void addStu(){
        Stage stage=new Stage();
        FXMLLoader loader=null;
        AddStuController addStuController=new AddStuController(user,course.getId(),this);
        Pane root=null;
        loader=new FXMLLoader(getClass().getResource("/Interface/AddStu.fxml"));
        loader.setController(addStuController);
        try {
            root=loader.load();
        } catch (IOException e) {
            System.out.println("添加学生界面挑战失败");
            e.printStackTrace();
        }
        Scene scene=new Scene(root);
        stage.setScene(scene);
        stage.getIcons().add(new Image("/Interface/Icon.png"));
        stage.setTitle("添加学生");
        stage.setResizable(false);
        stage.show();
    }
    public void flush(Vector<User> student){
        user.clear();
        for(int i=0;i<student.size();i++){
            user.add(student.get(i));
        }
    }
    @FXML
    public void description(){

    }
    @FXML
    public void deleCourse(){
        Alert alert = new Alert(Alert.AlertType.WARNING);
        alert.setTitle("警告");
        alert.setHeaderText("注销课程");
        alert.setContentText("确定要进行该操作吗？");
        ButtonType buttonTypeOK = new ButtonType("确定", ButtonBar.ButtonData.OK_DONE);
        alert.getButtonTypes().setAll(buttonTypeOK);
        alert.setOnCloseRequest(event -> {
            if (alert.getResult() == buttonTypeOK) {
                Message ms=new Message();
                ms.setState(MessageType.Course_Logout);
                try {
                    ObjectOutputStream oos=new ObjectOutputStream(socket.getOutputStream());
                    oos.writeObject(ms);
                    oos.writeObject(course);
                    System.out.println("请求注销课程");
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Stage stage=(Stage) ID.getScene().getWindow();
                stage.close();
            }
        });
        alert.showAndWait();
    }
    public void close(){
        flag = false;
        service.cancel();
        System.out.println("停止刷新学生列表");
    }
    private ObservableList<Select> selectTask= FXCollections.observableArrayList();//选人活动数据源
    @FXML
    private ListView<Select> selectlist;
    @FXML
    private TextField taskName;
    @FXML
    private Label selectError;
    @FXML
    public void newSelect() {
        if (taskName.getText().equals("")) {
            selectError.setText("活动名称为空");
            return;
        }
        selectError.setText("");
        Select select = new Select(taskName.getText(),course.getId());
        try {
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            Message ms = new Message();
            ms.setState(MessageType.SelectTask_New);
            oos.writeObject(ms);
            oos.writeObject(select);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        taskName.clear();
        new Thread(()->{
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            Platform.runLater(() -> {
                selectFlush();
            });
        }).start();
    }
    public void selectFlush(){
        selectTask.clear();
        Vector<Select> selects=FlushCourse.selectMap.get(course.getId());
        for(int i=0;i<selects.size();i++){
            selectTask.add(0,selects.get(i));
        }
    }
    @FXML
    public void newHomework(){
        Stage stage=new Stage();
        FXMLLoader loader=null;
        NewHomeworkController newHomeworkController=new NewHomeworkController(this,course);
        Pane root=null;
        loader=new FXMLLoader(getClass().getResource("/Interface/NewHomework.fxml"));
        loader.setController(newHomeworkController);
        try {
            root=loader.load();
        } catch (IOException e) {
            System.out.println("发布作业界面跳转失败");
            e.printStackTrace();
        }
        Scene scene=new Scene(root);
        stage.setScene(scene);
        stage.getIcons().add(new Image("/Interface/Icon.png"));
        stage.setTitle("发布作业");
        stage.setResizable(false);
        stage.show();
    }
    @FXML
    private ListView<Topic> topiclist;
    private ObservableList<Topic> topicSource=FXCollections.observableArrayList();
    public void addTopic(Topic topic){
        topicSource.add(0,topic);
    }
    @FXML
    public void newAttendTask(){

    }
}
